#include "Item.h"
#include "Inventory.h"

bool Inventory::add(Item* itm) {
	if (m_items.size() < maxSize) {
		m_items.push_back(itm);
		
		bool success;
		char sym = 'a';
		do {
			success = mapInsert(itm, sym);
			if (!success) {
				sym++;
				if (sym > 'z') {
					sym = 'A';
				}
			}
		} while (!success);
		
	} else {
		return false;
	}
	return true;
}

bool Inventory::containSymbol(char sym) const {
	std::map<Item *, char>::const_iterator i = m_symbolMapping.begin();
	for (i; i != m_symbolMapping.end(); ++i) {
		if ((*i).second == sym)
			return true;
	}
	return false;
}
	
bool Inventory::mapInsert(Item* item, char sym) {
	if (containSymbol(sym))
		return false;
	
	std::map<Item *, char>::iterator i = m_symbolMapping.find(item);
	if (i == m_symbolMapping.end()) {
		m_symbolMapping.insert(std::make_pair(item, sym));
		return true;
	} else {
		return false;
	}
}

void Inventory::mapErase(Item* item) {
	std::map<Item *, char>::iterator i = m_symbolMapping.find(item);
	if (i != m_symbolMapping.end()) {
		m_symbolMapping.erase(i);
	}
}
	
Item* Inventory::drop(size_t index) {
	Item* itm = m_items[index];
	m_items[index]->drop();
	remove(index);
	
	mapErase(itm);
	
	return itm;
}
	
Item* Inventory::item(size_t index) const {
	return m_items[index];
}

Item* Inventory::itemBySymbol(char symbol) const {
	std::map<Item *, char>::const_iterator i = m_symbolMapping.begin();
	for (i; i != m_symbolMapping.end(); ++i) {
		if ((*i).second == symbol)
			return (*i).first;
	}
	return NULL;
}

char Inventory::itemSymbol(Item* item) const {
	std::map<Item *, char>::const_iterator i = m_symbolMapping.find(item);
	if (i != m_symbolMapping.end()) {
		return (*i).second;
	}
	return 0;
}

int Inventory::totalWeight() const {
	int sum = 0;
	std::vector<Item *>::const_iterator i;
	for (i = m_items.begin(); i != m_items.end(); ++i) {
		sum += (*i)->weight();
	}
	return sum;
}

void Inventory::remove(size_t index) {
	Item* itm = item(index);
	std::vector<Item *>::iterator i;
	for (i = m_items.begin(); i != m_items.end(); ++i) {
		if ((*i) == itm) {
			m_items.erase(i);
			break;
		} else {
			++i;
		}
	}
}